package org.ims.inv.web.action.system;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ims.inv.model.system.ModelAppUser;
import org.ims.inv.model.system.ModelAppUserProfile;
import org.ims.inv.web.action.BaseAppAction;
import org.ims.inv.web.util.ContextUtil;
import org.springframework.beans.BeanUtils;

import cn.trymore.core.exception.ServiceException;
import cn.trymore.core.log.LogAnnotation;
import cn.trymore.core.util.UtilString;
import cn.trymore.core.web.paging.PaginationSupport;
import cn.trymore.core.web.paging.PagingBean;

/**
 * Action: 系统用户管理
 * 
 * @author Jeccy.Zhao
 *
 */
public class SystemAccountAction
extends BaseAppAction
{
	/**
	 * The LOGGER
	 */
	private static final Logger LOGGER = Logger.getLogger(SystemAccountAction.class);
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 我的资料
	 */
	public ActionForward pageAccountProfile (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			request.setAttribute("entity", ContextUtil.getCurrentUser().getUserProfile());
			request.setAttribute("account", ContextUtil.getCurrentUser());
			
			// 查询用户资料中相关的数据字典
			request.setAttribute("dictDept", this.getDictionariesByType("DICT_PROFILE_DEPT"));
			request.setAttribute("dictDuty", this.getDictionariesByType("DICT_PROFILE_DUTY"));
			request.setAttribute("dictEducation", this.getDictionariesByType("DICT_PROFILE_EDU"));
			
			return mapping.findForward("page.sys.account.profile");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading user dialog page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 我的资料弹框页面
	 */
	public ActionForward dialogAccountProfile (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String accountId = request.getParameter("uid");
			if (this.isObjectIdValid(accountId))
			{
				ModelAppUserProfile entity = serviceAppUserProfile.findProfileByAccount(accountId);
				if (entity != null)
				{
					request.setAttribute("entity", entity);
					this.outWriteAllParameters(request);
					return mapping.findForward("dialog.sys.account.profile");
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("用户资料不存在: " + accountId));
				}
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("非法的用户数据ID:" + accountId));
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading user dialog page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 保存个人资料
	 */
	public ActionForward actionSaveAccountProfile (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String accountId = request.getParameter("uid");
			if (this.isObjectIdValid(accountId))
			{
				ModelAppUser user = ContextUtil.getCurrentUser();
				ModelAppUserProfile formEntity = (ModelAppUserProfile) form;
				ModelAppUserProfile entity = user.getUserProfile();
				if (entity != null)
				{
					BeanUtils.copyProperties(formEntity, entity, new String[]{"account","department","jobTitle","education"});
				}
				else
				{
					entity = formEntity;
				}
				
				entity.setDepartment(this.serviceAppDictionary.get(request.getParameter("departmentId")));
				entity.setJobTitle(this.serviceAppDictionary.get(request.getParameter("jobTitleId")));
				entity.setEducation(this.serviceAppDictionary.get(request.getParameter("educationId")));
				entity.setAccount(user);
				entity.setLastModifiedTime(new Date());
				
				if (UtilString.isNotEmpty(entity.getIntroduction()))
				{
					entity.setIntroduction(entity.getIntroduction().replaceAll("\\r\\n|\\r|\\n", "<br/>"));
				}
				
				this.serviceAppUserProfile.save(entity);
				
				user.setUserProfile(entity);
				this.serviceAppUser.save(user);
				
				return ajaxPrint(response, 
						getSuccessCallback("资料数据保存成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, false));
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("用户账号ID不能为空"));
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading user dialog page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 用户管理
	 */
	public ActionForward pageAccountIndex (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			ModelAppUser formEntity = (ModelAppUser) form;
			
			if (!ContextUtil.getCurrentUser().isSuperUser())
			{
				formEntity.setSuperFilter(true);
			}
			
			PagingBean pagingBean = this.getPagingBean(request);
			PaginationSupport<ModelAppUser> users = this.serviceAppUser.getPagination(formEntity, pagingBean);
			
			// 初始化用户权限信息
			if (users != null && users.getItemCount() > 0)
			{
				for (ModelAppUser user : users.getItems())
				{
					initUserRole(user);
				}
			}
			
			request.setAttribute("datagrid", users);
			request.setAttribute("formEntity", formEntity);
			
			this.outWriteAllParameters(request);
			
			// 输出分页信息至客户端
			outWritePagination(request, pagingBean, users);
			
		} 
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when fetch all users.", e);
		}
		
		return mapping.findForward("page.sys.account.index");
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 用户重置密码
	 */
	public ActionForward pageAccountResetPage (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		return mapping.findForward("page.sys.account.reset.index");
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 用户数据弹框页面
	 */
	public ActionForward dialogAccountPage (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String userId = request.getParameter("id");
			if (UtilString.isNotEmpty(userId))
			{
				if (this.isObjectIdValid(userId))
				{
					ModelAppUser user = this.serviceAppUser.get(userId);
					initUserRole(user);
					
					request.setAttribute("entity", user);
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("数据ID不合法!"));
				}
			}
			
			request.setAttribute("allRoles", getAllRoles());
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading user dialog page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
		
		return mapping.findForward("dialog.sys.account");
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 用户数据保存
	 */
	@LogAnnotation(description="账号添加或更新: `${userName}`",type="用户管理")
	public ActionForward actionSavaUser (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			ModelAppUser formEntity = (ModelAppUser)form;
			ModelAppUser entity = formEntity;
			
			boolean isActionEdit = this.isObjectIdValid(formEntity.getId());
			
			if (isActionEdit)
			{
				// 编辑
				entity = this.serviceAppUser.get(formEntity.getId());
				if (entity != null)
				{
					BeanUtils.copyProperties(formEntity, entity, 
							new String[] { "lastLogonIP", "lastLogonTime", "delFlag", "userRole", "userPassword", "userStatus" } );
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("用户数据实体不存在!"));
				}
			}
			else
			{
				// 新建, 设置初始密码
				entity.setUserPassword(UtilString.encryptSha256(entity.getUserNo()));
				entity.setUserStatus(ModelAppUser.STAT_NORMAL);
				entity.setDelFlag(ModelAppUser.FLAG_UNDEL);
			}
			
			entity.setUserRole(null);
			
			// 设置用户角色
			String[] userRoleIds = request.getParameterValues("roleId");
			if (UtilString.isNotEmpty(userRoleIds))
			{
				//String[] userRoleIds = paramUserRoleIds.split(",");
				entity.setUserRole(UtilString.join(userRoleIds, ","));
				/*
				for (String userRoleId : userRoleIds)
				{
					ModelAppRole role = this.serviceAppRole.get(userRoleId);
					if (role != null)
					{
						//entity.setUserRole(role);
						entity.setUserRole(userRoleId);
					}
					else
					{
						return ajaxPrint(response, getErrorCallback("用户角色不存在:" + userRoleId));
					}
				}
				*/
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("需指定用户角色信息!"));
			}
			
			// 保存
			this.serviceAppUser.save(entity);
			
			return ajaxPrint(response, 
					getSuccessCallback("数据保存成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, false));
		}
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when saving user data", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 唯一性检测用户编号
	 */
	public ActionForward actionUniqueCheckUserNo (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		String userNo = request.getParameter("userNo");
		
		if (UtilString.isNotEmpty(userNo))
		{
			try
			{
				if (this.serviceAppUser.findByUserNo(userNo) == null)
				{
					return ajaxPrint(response, AJAX_RESPONSE_TRUE);
				}
			} 
			catch (ServiceException e)
			{
				LOGGER.error("Exception raised when checking dict data", e);
			}
		}
		
		return ajaxPrint(response, AJAX_RESPONSE_FALSE);
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 用户重置密码
	 */
	@LogAnnotation(description="账号重置密码: `${id}`",type="用户管理")
	public ActionForward actionResetPassword (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String userId = request.getParameter("id");
			
			if (UtilString.isNotEmpty(userId))
			{
				ModelAppUser entity = this.serviceAppUser.get(userId);
				if (entity != null)
				{
					entity.setUserPassword(UtilString.encryptSha256(entity.getUserNo()));
					this.serviceAppUser.save(entity);
					return ajaxPrint(response, AJAX_RESPONSE_TRUE);
				}
			}
		}
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when resetting user password", e);
		}
		
		return ajaxPrint(response, AJAX_RESPONSE_FALSE);
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 用户更改密码
	 */
	@LogAnnotation(description="更改账号密码",type="密码修改")
	public ActionForward actionChangePassword (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String oldPassword = request.getParameter("oldPassword");
			String newPassword = request.getParameter("newPassword");
			String newPasswordAgain = request.getParameter("newPasswordAgain");
			
			if (!newPassword.equals(newPasswordAgain))
			{
				return ajaxPrint(response, getErrorCallback("两次输入的新密码不匹配, 请重新输入..."));
			}
			
			ModelAppUser currentUser = ContextUtil.getCurrentUser();
			if (currentUser.getPassword().equals(UtilString.encryptSha256(oldPassword)))
			{
				currentUser.setUserPassword(UtilString.encryptSha256(newPassword));
				
				this.serviceAppUser.save(currentUser);
				
				return ajaxPrint(response, 
						getSuccessCallbackAndReloadCurrent("账号密码更改成功."));
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("原账号密码不正确, 请重新输入..."));
			}
			
		}
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when resetting user password", e);
		}
		
		return ajaxPrint(response, AJAX_RESPONSE_FALSE);
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 用户冻结
	 */
	@LogAnnotation(description="账号冻结: `${id}`",type="用户管理")
	public ActionForward actionFreezeUser (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String userId = request.getParameter("id");
			this.changeUserStatus(userId, ModelAppUser.STAT_FROZEN);
			return ajaxPrint(response, AJAX_RESPONSE_TRUE);
		}
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when freezing user", e);
		}
		
		return ajaxPrint(response, AJAX_RESPONSE_FALSE);
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 用户激活
	 */
	@LogAnnotation(description="账号激活: `${id}`",type="用户管理")
	public ActionForward actionActivateUser (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String userId = request.getParameter("id");
			this.changeUserStatus(userId, ModelAppUser.STAT_NORMAL);
			return ajaxPrint(response, AJAX_RESPONSE_TRUE);
		}
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when activating user", e);
		}
		
		return ajaxPrint(response, AJAX_RESPONSE_FALSE);
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 用户数据移除
	 */
	@LogAnnotation(description="账号数据移除: `${id}`",type="用户管理")
	public ActionForward actionRemoveUser (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String userId = request.getParameter("id");
			if (this.isObjectIdValid(userId))
			{
				ModelAppUser user = this.serviceAppUser.get(userId);
				if (user != null)
				{
					user.setDelFlag(ModelAppUser.FLAG_DEL);
					this.serviceAppUser.removeUser(userId);
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("用户数据不存在:" + userId));
				}
				
				return ajaxPrint(response, 
					getSuccessCallbackAndReloadCurrent("用户数据删除成功."));
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("数据ID不合法!"));
			}
		}
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when removing user data", e);
			return ajaxPrint(response, getErrorCallback("数据删除失败,原因:" + e.getMessage()));
		}
		
	}
	
	/**
	 * 更改用户状态
	 * 
	 * @param userId
	 * @param status
	 * @throws ServiceException
	 */
	private void changeUserStatus (String userId, Integer status) throws ServiceException
	{
		if (UtilString.isNotEmpty(userId))
		{
			ModelAppUser entity = this.serviceAppUser.get(userId);
			if (entity != null)
			{
				entity.setUserStatus(status);
				this.serviceAppUser.save(entity);
			}
		}
	}
	
	public static Logger getLogger()
	{
		return LOGGER;
	}
}
